package com.example.dragon.fragment;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.example.dragon.adpter.CanceledAdpter;
import com.example.dragon.bean.OrderBean;
import com.example.dragon.bean.UserBean;
import com.example.dragon.common.Common;
import com.example.dragon.dialog.MessageDialog;
import com.example.dragon.dialog.WaitDialog;
import com.example.dragon.untis.CircleImageView;
import com.example.dragon.xmf.ConfirmOrderActivity;
import com.example.dragon.xmf.LoginActivity;
import com.example.dragon.xmf.MainActivity;
import com.example.dragon.xmf.ProblemActivity;
import com.example.dragon.xmf.R;
import com.example.dragon.xmf.UserInfoActivity;
import com.example.dragon.xmf.UserWebActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;

import static android.app.Activity.RESULT_OK;

public class UserFragment extends Fragment implements View.OnClickListener{

    private TextView muserNameText;
    private CircleImageView muserAvatar;
    private String mCurrentPhotoPath,mffilePath, imgUrl;
    private WaitDialog mWaitDialog;
    private SharedPreferences sp;
    private int RESULT_LOAD_IMAGE=0,RESULT_CAMERA_IMAGE=2;
    private UserBean muserBean;
    private RelativeLayout kefu, shoufeiRL,xieyiRL,wentiRL,guanyuRL;
    private LinearLayout outlogin;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_user,null);
        initControls(view);
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            //可见
            getUserInfo();
        }else{
            //不可见
        }
    }

    private void initControls(View view) {
        mWaitDialog = new WaitDialog(getContext(),"5");
        getUserInfo();
        TextView acbTitle = (TextView)view.findViewById(R.id.acbTitle);
        acbTitle.setText("我的");
        shoufeiRL = (RelativeLayout) view.findViewById(R.id.shoufeiRL);
        xieyiRL = (RelativeLayout) view.findViewById(R.id.xieyiRL);
        wentiRL = (RelativeLayout) view.findViewById(R.id.wentiRL);
        guanyuRL = (RelativeLayout) view.findViewById(R.id.guanyuRL);
        muserNameText = (TextView)view.findViewById(R.id.user_name);
        kefu = (RelativeLayout)view.findViewById(R.id.kefu);
        muserAvatar = (CircleImageView)view.findViewById(R.id.user_avatar);
        outlogin = (LinearLayout)view.findViewById(R.id.outLogin);
        sp = getActivity().getSharedPreferences("userInfo", 0);
        mffilePath = sp.getString("filePath",null);
        imgUrl = sp.getString("avter",null);
        Glide.with(getContext()).load(mffilePath+imgUrl).into(muserAvatar);
        mWaitDialog = new WaitDialog(getContext(),"2");
        shoufeiRL.setOnClickListener(this);
        xieyiRL.setOnClickListener(this);
        wentiRL.setOnClickListener(this);
        guanyuRL.setOnClickListener(this);
        kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getdata();
            }
        });
        muserNameText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(),UserInfoActivity.class);
                startActivityForResult(intent,0);
//                startActivity(new Intent(getContext(), UserInfoActivity.class));
            }
        });
        outlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MessageDialog2();
            }
        });
        muserAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopueWindow();
            }
        });
    }
    private void showPopueWindow(){
        View popView = View.inflate(getContext(),R.layout.popupwindow_camera_layout,null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
        //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels*1/3;

        final PopupWindow popupWindow = new PopupWindow(popView,weight,height);
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
                popupWindow.dismiss();

            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takeCamera(RESULT_CAMERA_IMAGE);
                popupWindow.dismiss();

            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1.0f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.5f;
        getActivity().getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);
    }
    private void takeCamera(int num) {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            photoFile = createImageFile();
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                Log.e("currentapiVersion","currentapiVersion====>"+currentapiVersion);
                if (currentapiVersion<24){
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    startActivityForResult(intent, num);
                }else {
                    ContentValues contentValues = new ContentValues(1);
                    contentValues.put(MediaStore.Images.Media.DATA, photoFile.getAbsolutePath());
                    Uri uri = getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent, num);
                }
            }
        }
    }


    private File createImageFile() {
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File image = null;
        try {
            image = File.createTempFile(
                    generateFileName(),  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    public static String generateFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        return imageFileName;
    }

    private void getdata(){
        OkHttpUtils.post()
                .url(Common.MIFENG_URL+"System&a=getContent")
                .addParams("field","phone")
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("res",e.toString());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("res",response.toString());
                        try {
                            JSONObject jsonObject =new JSONObject(response);
                            int code = jsonObject.getInt("code");
                            if (code==200){
                                String  datas = jsonObject.getString("datas");
                                MessageDialog(datas);
                            }else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK ) {
            if (requestCode == RESULT_LOAD_IMAGE && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor =getActivity().getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                final String picturePath = cursor.getString(columnIndex);
                File file =new File(picturePath);
                try {
                    uploadFile(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                cursor.close();
            }else if (requestCode == RESULT_CAMERA_IMAGE){

                SimpleTarget target = new SimpleTarget<Bitmap>() {

                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        try {
                            uploadFile(saveMyBitmap(resource).getAbsoluteFile());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onLoadStarted(Drawable placeholder) {
                        super.onLoadStarted(placeholder);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);

                    }
                };

                Glide.with(getContext()).load(mCurrentPhotoPath)
                        .asBitmap()
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .override(1080, 1920)//图片压缩
                        .centerCrop()
                        .dontAnimate()
                        .into(target);


            }
        }else if(resultCode==10){
            muserNameText.setText(data.getExtras().getString("username"));
        }
    }
    //将bitmap转化为png格式
    public File saveMyBitmap(Bitmap mBitmap){
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File file = null;
        try {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy/MM/dd/hh/mm/ss");
            String date = sDateFormat.format(new java.util.Date());
            file = File.createTempFile(generateFileName(),".jpg",storageDir);
            FileOutputStream out=new FileOutputStream(file);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  file;
    }

    private void getUserInfo(){
        OkHttpUtils.post()
                .url(Common.MIFENG_URL+"User&a=getInfo")
                .addParams("token",MainActivity.TOKEN)
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("res",e.toString());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("res",response.toString());
                        try {
                            JSONObject jsonObject =new JSONObject(response);
                            int code = jsonObject.getInt("code");
                            if (code==200){
                                JSONObject jsonObject1 = jsonObject.getJSONObject("datas");
                                muserBean = new UserBean(
                                        jsonObject1.getString("user_id"),
                                        jsonObject1.getString("mobile"),
                                        jsonObject1.getString("name"),
                                        jsonObject1.getString("avatar"),
                                        jsonObject1.getString("idcard")
                                );
                                if (muserBean.getName().equals("")){
                                    muserNameText.setText(muserBean.getMobile());
                                }else {
                                    muserNameText.setText(muserBean.getName());
                                }

                                Glide.with(getContext()).load(muserBean.getAvatar()).error(R.mipmap.ic_launcher).placeholder(R.mipmap.ic_launcher).into(muserAvatar);
                                Log.i("datas",muserBean.getUser_id());
                            }else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    private void uploadFile(File picturePath) throws Exception {
        mWaitDialog.show();
        OkHttpUtils.post()
                .addFile("filesrc", picturePath.getName(), picturePath)
                .url(Common.MIFENG_URL+"Public&a=upload")
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("res",e.toString());
                        mWaitDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("res",response.toString());
                        mWaitDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int code = jsonObject.getInt("code");
                            if (code==200){
                                Log.i("gg",jsonObject.getString("datas"));
                                imgUrl = mffilePath+ jsonObject.getString("datas");
                                postAcater(jsonObject.getString("datas"));
                            }else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    private void postAcater(final String imgurl){
        OkHttpUtils.post()
                .url(Common.MIFENG_URL+"User&a=postAvatar")
                .addParams("token",MainActivity.TOKEN)
                .addParams("avatar",imgurl)
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("res",e.toString());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("res",response.toString());
                        try {
                            JSONObject jsonObject =new JSONObject(response);
                            int code = jsonObject.getInt("code");
                            if (code==200){
                                JSONObject avter = jsonObject.getJSONObject("datas");
                                SharedPreferences.Editor editor = sp.edit();
                                editor.putString("avter",avter.getString("avatar"));
                                editor.commit();
                                Log.i("avter",avter.getString("avatar"));
                                Glide.with(getContext()).load(mffilePath+avter.getString("avatar")).into(muserAvatar);
                            }else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void MessageDialog(final CharSequence message){
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示");
        builder.setMessage("是否呼叫:"+message);
        builder.setPositiveButton("呼叫", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + message);
                intent.setData(data);
                startActivity(intent);
                dialogInterface.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }
    public void MessageDialog2(){
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示");
        builder.setMessage("是否退出");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                SharedPreferences.Editor editor = sp.edit();
                editor.clear();
                editor.commit();
                getActivity().finish();
                startActivity(new Intent(getContext(), LoginActivity.class));
                dialogInterface.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.shoufeiRL:
                getWebUrl("charge","收费标准");
                break;
            case R.id.xieyiRL:
                getWebUrl("xieyi","用户协议");
                break;
            case R.id.wentiRL:
                startActivity(new Intent(getContext(), ProblemActivity.class));
                break;
            case R.id.guanyuRL:
                getWebUrl("about","关于我们");
                break;
        }
    }
    private void getWebUrl(String field, final String title){
        Log.i("zwtttt","load......");
        OkHttpUtils.post()
                .url(Common.MIFENG_URL+"System&a=getArticle")
                .addParams("token",MainActivity.TOKEN)
                .addParams("field",field)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("res",e.toString());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("res",response.toString());
                        try {
                            JSONObject jsonObject =new JSONObject(response);
                            int code = jsonObject.getInt("code");
                            if (code==200){
                                String datas = jsonObject.getString("datas");
                                Log.i("zwtttt","load......"+datas);
                                showUserWebActivity(datas,title);
                            }else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }
    private void showUserWebActivity(String url,String title){
        Intent intent  = new Intent(getContext(), UserWebActivity.class);
        intent.putExtra("url",url);
        intent.putExtra("title",title);
        startActivity(intent);
    }
}
